package com.platform.file.controller;

import java.io.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.core.constant.CacheConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.redis.service.RedisService;
import com.platform.common.security.annotation.RequiresPermissions;
import com.platform.common.security.utils.AESUtil_SC;
import com.platform.file.constant.SysFileConstants;
import com.platform.file.domain.DicFileLog;
import com.platform.file.service.IDicFileLogService;
import com.platform.file.service.ISysFileService;
import com.platform.file.utils.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
//import com.platform.common.fileLog.annotation.Log;
//import com.platform.common.fileLog.enums.BusinessType;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.core.utils.poi.ExcelUtil;
import com.platform.common.core.web.page.TableDataInfo;

/**
 * 文件操作日志Controller
 *
 * @author platform
 * @date 2023-05-08
 */
@Slf4j
@RestController
@RequestMapping("/fileLog")
public class DicFileLogController extends BaseController
{

    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private IDicFileLogService dicFileLogService;
    @Autowired
    private RedisService redisService;
    /**
     * 资源映射路径 前缀
     */
    @Value("${minio.filePrefix}")
    ///statics
    public String filePrefix;
    @Value("${minio.bucketName}")
    ///statics
    public String bucketName;
    /**
     * 查询文件操作日志列表
     */
//    @RequiresPermissions("file:fileLog:list")
    @GetMapping("/list")
    public TableDataInfo list(DicFileLog dicFileLog)
    {
        startPage();
        List<DicFileLog> list = dicFileLogService.selectDicFileLogList(dicFileLog);
        return getDataTable(list);
    }

    /**
     * 导出文件操作日志列表
     */
    @RequiresPermissions("file:fileLog:export")
    //@Log(title = "文件操作日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DicFileLog dicFileLog)
    {
        List<DicFileLog> list = dicFileLogService.selectDicFileLogList(dicFileLog);
        ExcelUtil<DicFileLog> util = new ExcelUtil<DicFileLog>(DicFileLog.class);
        util.exportExcel(response, list, "文件操作日志数据");
    }

    /**
     * 获取文件操作日志详细信息
     */
//    @RequiresPermissions("file:fileLog:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(dicFileLogService.selectDicFileLogById(id));
    }

    /**
     * 新增文件操作日志
     */
    @RequiresPermissions("file:fileLog:add")
    //@Log(title = "文件操作日志", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DicFileLog dicFileLog)
    {
        return toAjax(dicFileLogService.insertDicFileLog(dicFileLog));
    }

    /**
     * 修改文件操作日志
     */
    @RequiresPermissions("file:fileLog:edit")
    //@Log(title = "文件操作日志", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DicFileLog dicFileLog)
    {
        return toAjax(dicFileLogService.updateDicFileLog(dicFileLog));
    }

    /**
     * 删除文件操作日志
     */
    @RequiresPermissions("file:fileLog:remove")
    //@Log(title = "文件操作日志", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dicFileLogService.deleteDicFileLogByIds(ids));
    }


    /**
     * 获取 图片回显的 guid
     * @return
     * @throws Exception
     */
    @GetMapping("/getGuid")
    public R getGuid(@RequestParam("num")Integer num){
        try {
            R responseResult=R.ok();
            String uuid= UUID.randomUUID().toString().trim().replaceAll("-", "");
            //后端限制最大访问次数
            if(num> SysFileConstants.MAX_NUM){
                num=SysFileConstants.MAX_NUM;
            }
            redisService.setCacheObject(uuid, num, CacheConstants.EXPIRATION, TimeUnit.MINUTES);
            responseResult.setData(uuid);
            return responseResult;

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }
    /**
     * 获取 图片完整路径
     * @return
     * @throws Exception
     */
    @GetMapping("/getCompleteUrl")
//    @RequiresPermissions("file:fileLog:getCompleteUrl")
    public R getCompleteUrl(@RequestParam("fileUrl") String fileUrl){
        try {
            String returnPath =filePrefix+'/'+bucketName+'/';
            return R.ok(returnPath+fileUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }
    /**
     * 查看图片服务接口
     */
    @GetMapping("/previewFile")
//    @RequiresPermissions("file:fileLog:previewFile")
    public void previewFile(@RequestParam("fileUrl") String fileUrl, String guid,String type, HttpServletResponse response){
        try {
            //guid权限校验
            if (StringUtils.isEmpty(guid)) {
                returnResponseResult(response,R.FAIL,"guid权限校验失败");
                return;
            }else{
                if(redisService.hasKey(guid)){
                    Integer num=redisService.getCacheObject(guid);
                    if(num==null|| num.equals(SysFileConstants.ZERO)){
                        returnResponseResult(response,R.FAIL,"guid权限校验失败");
                    }
                    //访问次数-1
                    num--;
                    if(num>SysFileConstants.ZERO){
                        //修改次数
                        redisService.setCacheObject(guid,num);
                    }else if(num.equals(SysFileConstants.ZERO)){
                        //删除
                        redisService.deleteObject(guid);
                    }
                }else {
                    returnResponseResult(response,R.FAIL,"guid权限校验失败");
                }

            }
            //参数校验
            if(StringUtils.isEmpty(fileUrl)){
                returnResponseResult(response,R.FAIL,"文件路径不能为空");
                return;
            }else {
                try {
                    InputStream fileStream = sysFileService.downLoadFile(fileUrl);
                    if(fileStream!=null){
                        if("1".equals(type)){
                            //预览
                        }else if("2".equals(type)){
                            //如果需要下载文件，去掉下面的注释
                            response.setHeader("content-disposition", "attachment;");
                        }

                        OutputStream outputStream = response.getOutputStream();
                        int len = 0;
                        byte[] data = new byte[1024];
                        while ((len = fileStream.read(data)) != -1) {
                            outputStream.write(data, 0, len);
                        }
                        outputStream.close();
                        fileStream.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("获取文件流失败", e);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查看图片服务接口
     */
    @GetMapping("/previewFileNew")
//    @RequiresPermissions("file:fileLog:previewFile")
    public void previewFileNew(@RequestParam("fileUrl") String fileUrl, String guid,String type, HttpServletResponse response){
        try {
            //guid权限校验
            if (StringUtils.isEmpty(guid)) {
                returnResponseResult(response,R.FAIL,"guid权限校验失败");
                return;
            }else{
                if(redisService.hasKey(guid)){
                    Integer num=redisService.getCacheObject(guid);
                    if(num==null|| num.equals(SysFileConstants.ZERO)){
                        returnResponseResult(response,R.FAIL,"guid权限校验失败");
                    }
                    //访问次数-1
                    num--;
                    if(num>SysFileConstants.ZERO){
                        //修改次数
                        redisService.setCacheObject(guid,num);
                    }else if(num.equals(SysFileConstants.ZERO)){
                        //删除
                        redisService.deleteObject(guid);
                    }
                }else {
                    returnResponseResult(response,R.FAIL,"guid权限校验失败");
                }
            }
            //参数校验
            if(StringUtils.isEmpty(fileUrl)){
                returnResponseResult(response,R.FAIL,"文件路径不能为空");
                return;
            }else {
                try {
                    String minioPath= AESUtil_SC.decryptNoBase64(fileUrl,SysFileConstants.FILESECRET);
                    String bucketName= FileUploadUtils.getBucketName(minioPath);
                    if(StringUtils.isEmpty(bucketName)){
                        returnResponseResult(response,R.FAIL,"文件路径不正确");
                        return;
                    }
                    // 获取输入流和输出流
                    InputStream fileStream = sysFileService.downLoadFileNew(bucketName,minioPath.replace(bucketName+"/",""));
                    if(fileStream!=null){
                        if("1".equals(type)){
                            //预览
                        }else if("2".equals(type)){
                            //如果需要下载文件，去掉下面的注释
                            response.setHeader("content-disposition", "attachment;");
                        }

                        OutputStream outputStream = response.getOutputStream();
                        int len = 0;
                        byte[] data = new byte[1024];
                        while ((len = fileStream.read(data)) != -1) {
                            outputStream.write(data, 0, len);
                        }
                        outputStream.close();
                        fileStream.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("获取文件流失败", e);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看图片服务接口
     */
    @GetMapping("/previewFileApi")
    public void previewFileApi(@RequestParam("fileUrl") String fileUrl,String type, HttpServletResponse response){
        try {
            //参数校验
            if(StringUtils.isEmpty(fileUrl)){
                returnResponseResult(response,R.FAIL,"文件路径不能为空");
                return;
            }else {
                try {
                    String minioPath= AESUtil_SC.decryptNoBase64(fileUrl,SysFileConstants.FILESECRET);
                    String bucketName= FileUploadUtils.getBucketName(minioPath);
                    if(StringUtils.isEmpty(bucketName)){
                        returnResponseResult(response,R.FAIL,"文件路径不正确");
                        return;
                    }
                    // 获取输入流和输出流
                    InputStream fileStream = sysFileService.downLoadFileNew(bucketName,minioPath.replace(bucketName+"/",""));
                    if(fileStream!=null){
                        if("1".equals(type)){
                            //预览
                        }else if("2".equals(type)){
                            //如果需要下载文件，去掉下面的注释
                            response.setHeader("content-disposition", "attachment;");
                        }

                        OutputStream outputStream = response.getOutputStream();
                        int len = 0;
                        byte[] data = new byte[1024];
                        while ((len = fileStream.read(data)) != -1) {
                            outputStream.write(data, 0, len);
                        }
                        outputStream.close();
                        fileStream.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("获取文件流失败", e);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 返回响应信息
     */
    private void returnResponseResult(ServletResponse response, int code, String msg) throws IOException {
        PrintWriter writer = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(response.getOutputStream(), "GBK");
            writer = new PrintWriter(osw, true);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", code);
            jsonObject.put("message", msg);
            writer.write(jsonObject.toJSONString());
            writer.flush();
            writer.close();
            osw.close();
        } catch (Exception e) {
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != osw) {
                osw.close();
            }
        }
    }

}
